package cc.eddic.pratice.programmingparadigms.emp02list.impl;

import cc.eddic.pratice.programmingparadigms.Result;
import cc.eddic.pratice.programmingparadigms.ResultComparator;
import cc.eddic.pratice.programmingparadigms.ResultPredicate;
import cc.eddic.pratice.programmingparadigms.emp02list.ResultList;

import java.util.Objects;

public class ResultListCxyImpl implements ResultList {

    private Result[] results;
    private int index;

    public ResultListCxyImpl(int capacity) {
        results = new Result[capacity];
        index = 0;
    }



    @Override
    public void add(Result result) {
        if (index + 1 > results.length) {
            Result[] resultNew = new Result[results.length * 2];
            System.arraycopy(results, 0, resultNew, 0, index + 1);
            results = resultNew;
        }
        results[index] = result;
        index++;
    }

    @Override
    public Result get(int index) {
        if(index>size()-1) {
            throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size());
        }else return results[index];
    }

    @Override
    public int size() {
        return index;
    }

    @Override
    public Result findByGender(String gender) {
        for (Result result : results) {
            if (Objects.equals(result.getKey(), gender))
                return result;
        }
        return null;
    }

    @Override
    public Result findByDepartment(String department) {
        for (Result result : results) {
            if (Objects.equals(result.getKey(), department))
                return result;
        }
        return null;
    }

    @Override
    public Result findByJobTitle(String jobTitle) {
        for (Result result : results) {
            if (Objects.equals(result.getKey(), jobTitle))
                return result;
        }
        return null;
    }

    @Override
    public Result find(ResultPredicate predicate) {
        for (int i = 0; i < size(); ++i) {
            Result r = get(i);
            if (predicate.test(r)) {
                return r;
            }
        }
        return null;
    }

    @Override
    public void sort(ResultComparator comparator) {
        // 冒泡排序
        for (int i = 0; i < size(); i++) {
            for (int j = 0; j < size() - i - 1; j++) {
                // 什么情况下要交换
                if (comparator.compare(results[j], results[j + 1]) > 0) {
                    // 交换
                    Result temp = results[j];
                    results[j] = results[j + 1];
                    results[j + 1] = temp;
                }
            }
        }
    }
}
